#include "ToolButtonShell.h"
#include <QAction>
#include <QMenu>
#include <QIcon>

#define kKeyType "type"
#define kKeyText "text"
#define kKeyIcon "icon"
#define kKeyName "name"
#define kKeyCheckable "checkable"
#define kKeyChecked "checked"
#define kKeyUserInfo "userInfo"

#define kValueAction "action"

ToolButtonPopupShell::ToolButtonPopupShell(QToolButton *toolButton){
    shell(toolButton);
}
ToolButtonPopupShell::ToolButtonPopupShell(){
    _target = nullptr;
}
ToolButtonPopupShell::~ToolButtonPopupShell(){

}

void ToolButtonPopupShell::shell(QToolButton *toolButton){
    if(nullptr != _target){
        return;
    }
    _target = toolButton;
    _target->setPopupMode(QToolButton::MenuButtonPopup);
    connect(_target, &QToolButton::triggered,this,&ToolButtonPopupShell::onTriggered);
}

void setData(const QJsonObject &object){

}

void addItems(const QJsonArray &array);

void ToolButtonPopupShell::addActions(const QJsonArray &array){
    for(int index=0; index<array.count(); index++){
        addAction(array[index].toObject());
    }
}
void ToolButtonPopupShell::addAction(const QJsonObject &object){
    QString text = object.contains(kKeyText) ? object[kKeyText].toString() : "";
    QString icon = object.contains(kKeyIcon) ? object[kKeyIcon].toString() :"";
    QString name = object.contains(kKeyName) ? object[kKeyName].toString() :"";
    QVariant userInfo = object.contains(kKeyUserInfo) ? object[kKeyUserInfo].toVariant() : QVariant();

    QMenu *menu = this->menu();
    if(nullptr == menu){
        menu = new QMenu(_target);
        _target->setMenu(menu);
    }
    auto action = menu->addAction(QIcon(icon),text);
    action->setData(object);
}

QMenu *ToolButtonPopupShell::menu(){
    QMenu *menu = _target->menu();
    if(nullptr == menu){
        menu = new QMenu(_target);
        _target->setMenu(menu);
    }
    return menu;
}

void ToolButtonPopupShell::onTriggered(QAction *action){
    QJsonObject jsonObject = action->data().toJsonObject();
    QString name = jsonObject[kKeyName].toString();
    QVariant userInfo = jsonObject.contains(kKeyUserInfo)?jsonObject[kKeyUserInfo].toVariant():QVariant();
    emit sigClicked(name,action->isChecked(),userInfo);
}
